package com.yufu.plugins.tencent.qq;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import androidx.activity.result.ActivityResult;
import androidx.appcompat.app.AppCompatActivity;
import com.getcapacitor.Bridge;
import com.getcapacitor.JSObject;
import com.getcapacitor.PermissionState;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginConfig;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.ActivityCallback;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.DefaultUiListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONException;
import org.json.JSONObject;

@CapacitorPlugin(name = "TencentQQ", requestCodes = { Constants.REQUEST_LOGIN, Constants.REQUEST_APPBAR })
public class TencentQQPlugin extends Plugin {

    private final TencentQQ implementation = new TencentQQ();

    private static Tencent mTencent;

    private static AppCompatActivity activity;

    private static PluginCall currentCall;

    private static PluginConfig config;

    @Override
    public void load() {
        super.load();
        activity = this.getActivity();
        config = this.getConfig();
        String appId = config.getString("appId");
        Tencent.setIsPermissionGranted(true, Build.MODEL);
        mTencent = Tencent.createInstance(appId, this.getContext(), this.getAppId() + ".fileprovider");
    }

    @PluginMethod
    public void isQQInstalled(PluginCall call) {
        boolean isInstalled = mTencent.isQQInstalled(activity);
        JSObject ret = new JSObject();
        ret.put("installed", isInstalled);
        call.resolve(ret);
    }

    @PluginMethod
    public void login(PluginCall call) {
        currentCall = call;
        if (mTencent.isSessionValid()) {
            mTencent.logout(activity);
        }

        String type = call.getString("type");
        if (type == null) {
            type = "sso";
        }
        switch (type) {
            case "sso":
                mTencent.login(activity, "all", loginListener);
                break;
            case "server-side":
                mTencent.loginServerSide(activity, "all", loginListener);
                break;
        }
        // startActivityForResult(call,activity.getIntent(),"loginCallback");
    }

    @Override
    protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        }
        super.handleOnActivityResult(requestCode, resultCode, data);
    }

    private static class BaseUiListener extends DefaultUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                Log.d("SDKQQAgentPref", "登录失败:返回为空");
                // Util.showResultDialog(MainActivity.this, "返回为空", "登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (jsonResponse.length() == 0) {
                Log.d("SDKQQAgentPref", "登录失败:返回为空");
                // Util.showResultDialog(MainActivity.this, "返回为空", "登录失败");
                return;
            }
            Log.d("SDKQQAgentPref", "登录成功:" + response.toString());
            // Util.showResultDialog(MainActivity.this, response.toString(), "登录成功");

            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {}

        @Override
        public void onError(UiError e) {
            // Util.toastMessage(MainActivity.this, "onError: " + e.errorDetail);
            // Util.dismissDialog();
        }

        @Override
        public void onCancel() {
            Log.d("SDKQQAgentPref", "onCancel取消登录:" + SystemClock.elapsedRealtime());
            // Util.toastMessage(MainActivity.this, "onCancel: ");
            // Util.dismissDialog();
            // if (isServerSideLogin) {
            // isServerSideLogin = false;
            // }
        }
    }

    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            JSObject jsObject = null;
            try {
                jsObject = new JSObject(values.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (jsObject == null) {
                currentCall.reject("");
            } else {
                currentCall.resolve(jsObject);
            }
        }
    };
}
